package com.graduation.vaccine.config;

import com.graduation.vaccine.exception.GlobalException;
import com.graduation.vaccine.mapper.AppointmentMapper;
import com.graduation.vaccine.mapper.DepartmentProductionMapper;
import com.graduation.vaccine.pojo.Appointment;
import com.graduation.vaccine.pojo.DepartmentProduction;
import com.graduation.vaccine.vo.RespBeanEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @Author:CaiShuangLian
 * @FileName:
 * @Date:Created in  2022/4/23 14:42
 * @Version:
 * @Description:定时任务
 */
@Configuration
@EnableScheduling//开启定时任务
public class StaticScheduleTask {

    @Autowired
    private AppointmentMapper appointmentMapper;
    @Autowired
    private DepartmentProductionMapper departmentProductionMapper;

    @Scheduled(cron = "0 0 23 * * ?")
//    @Scheduled(fixedRate = 5000)
    @Transactional(rollbackFor = Exception.class)
    void configureTask(){
        //判断预约是否过期
        System.out.println("进入定时任务");
        List<Appointment> appointments=appointmentMapper.getAll();
        for(Appointment appointment:appointments){
            Date currentDay=new Date(System.currentTimeMillis());
            Long diff=currentDay.getTime()-appointment.getAppointmentTime().getTime();//得到毫秒数
            int status=appointment.getState();
            System.out.println("间隔时间"+(diff-1*24*60*60*1000)+"，当前状态"+status);
            //过期（1天）
            if(diff>=1*24*60*60*1000 && status==1){
                //将状态设置为3，表示逾期未接种
                appointment.setState(3);
                int row1=appointmentMapper.updateById(appointment);
                //同时库存加一
                DepartmentProduction departmentProduction=departmentProductionMapper.getTotalByDepartmentCodeAndProductionId(appointment.getDepartmentcode(),appointment.getProductionId());
                int row2=departmentProductionMapper.addTotal(departmentProduction.getDepartmentCode(),departmentProduction.getProductionId(),departmentProduction.getVersion());
                //更新失败抛出异常
                if(row1<=0 || row2<=0){
                    throw new GlobalException(RespBeanEnum.UPDATE_ERROR);
                }
            }
        }
    }
}
